<script setup>
import { ref, reactive, watch, onMounted, h, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { eventv1Api as MainApi, eventv1ById as MainById } from '@T2/service/api.ts';
import { useCurrentWatchStore, useIuserInfoStore } from '@T2/store/users.ts';
import UnitByPosition from '@T2/views/Project/Manage/components/select/unitByPosition.vue';
import UploadImage from '@T2/components/uploadImage/index.vue';
import UploadAttachment from '@T2/components/uploadAttachment/index.vue';
import Step from './step.vue';

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;
const iuserInfoStore = useIuserInfoStore();
const { info, getHandleRight } = iuserInfoStore;
const RIGHT = getHandleRight(['363', '364', '365', '366', '367', '368', '369']);

onMounted(() => {
  GetMainTable();
});

const MainTable = reactive({
  data: [],
  total: 0,
});
const Filter = reactive({
  page: 1,
  pagesize: 30,
  ordering: '-create_time',
  search: '',
});
const statusColor = {
  '待派单': '#0079FE',
  '待接单': '#0079FE',
  '待处理': '#FF7D00',
  '待验收': '#FF0000',
  '已完成': '#00B42A'
};
watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    Filter.page = 1;
  }
});
const GetMainTable = () => {
  MainApi({
    method: 'get',
    params: {
      ...Filter,
    }
  }).then(res => {
    MainTable.data = res?.results || [];
    MainTable.total = res?.count || 0;
  });
}


/* 新增编辑 */
const MainPopup = reactive({
  visible: false,
  type: '新增',
});
const MainForm = reactive({
  model: {},
  files_json: [],
  files_updateTimes: 0,
  fj_json: [],
  fj_updateTimes: 0,
});
const MainFormRef = ref(null);
const handleMainAdd = (isAble = false) => {
  if (!isAble) {
    return;
  }
  MainPopup.visible = true;
  MainPopup.type = '新增';
  MainForm.model = {};
  MainForm.files_json = [];
  MainForm.files_updateTimes++;
  MainForm.fj_json = [];
  MainForm.fj_updateTimes++;
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const handleMainEdit = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  MainPopup.visible = true;
  MainPopup.type = '编辑';
  MainForm.model = {
    id: row.id,
    unit: row.unit,
    position: row.position,
    addr: row.addr,
    type: row.type,
    level: row.level,
    describe: row.describe,
    files: row.files,
    fj: row.fj,
  };
  MainForm.files_json = row.files_json || [];
  MainForm.files_updateTimes++;
  MainForm.fj_json = row.fj_json || [];
  MainForm.fj_updateTimes++;
  nextTick(() => {
    MainFormRef.value.clearValidate();
  });
}
const unitChange = (data, node) => {
  if (data.hasOwnProperty('positon')) {
    MainForm.model.unit = data.id;
    MainForm.model.position = data.positon;
    MainForm.model.addr = data.addr;
  }
}
/* 上传资料 */
const filesChange = (files) => {
  MainForm.model.files = files;
}
const fjChange = (files) => {
  MainForm.model.fj = files;
}
const handleMainSubmit = () => {
  MainFormRef.value.validate((valid) => {
    if (valid) {
      MainPopup.visible = false;
      if (MainPopup.type === '新增') {
        AddMain();
      } else if (MainPopup.type === '编辑') {
        EditMain();
      }
    }
  });
}
const AddMain = () => {
  MainApi({
    method: 'post',
    data: {
      ...MainForm.model,
      comefrom: '创建工单',
      project: curProject.id,
      status: '待派单',
      creater: info.id,
    }
  }).then(res => {
    ElMessage.success('新增成功');
    GetMainTable();
  });
}
const EditMain = () => {
  MainById({
    method: 'patch',
    id: MainForm.model.id,
    data: {
      ...MainForm.model,
    }
  }).then(res => {
    ElMessage.success('编辑成功');
    GetMainTable();
  });
}
const handleMainDelete = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, `是否要删除编号： GD-${ row.id } 工单信息？`),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    MainById({
      method: 'delete',
      id: row.id,
    }).then(res => {
      ElMessage.success('删除成功');
      GetMainTable();
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}

/* 流程step相关 */
const stepPopup = reactive({
  type: '',   //['详情', '派单', '接单', '处理', '验收']
  content: {},
});
const stepTypeMap = {
  '已完成': '详情',
  '待派单': '派单',
  '待接单': '接单',
  '待处理': '处理',
  '待验收': '验收',
};
const handleStepView = (row) => {
  stepPopup.type = '详情';
  stepPopup.content = row;
}
const handleStep = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  stepPopup.type = stepTypeMap[row.status];
  stepPopup.content = row;
}
const closeStepMain = (refresh) => {
  stepPopup.type = '';
  stepPopup.content = {};
  if (refresh) {
    GetMainTable();
  }
}
</script>

<template>
  <div class="view flex">
    <div class="mtncOrder-box flex-column mainCard">
      <el-form label-width="120px" class="flex t_form">
        <el-form-item label="工单类型：">
          <el-select v-model="Filter.type" clearable>
            <el-option value="设备异常" label="设备异常"></el-option>
            <el-option value="系统异常" label="系统异常"></el-option>
            <el-option value="设备维护" label="设备维护"></el-option>
            <el-option value="生产事故" label="生产事故"></el-option>
            <el-option value="其他事件" label="其他事件"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单来源：">
          <el-select v-model="Filter.comefrom" clearable>
            <el-option value="创建工单" label="创建工单"></el-option>
            <el-option value="故障上报" label="故障上报"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态：">
          <el-select v-model="Filter.status" clearable>
            <el-option value="待派单" label="待派单"></el-option>
            <el-option value="待接单" label="待接单"></el-option>
            <el-option value="待处理" label="待处理"></el-option>
            <el-option value="待验收" label="待验收"></el-option>
            <el-option value="已完成" label="已完成"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模糊查询：">
          <el-input v-model="Filter.search" clearable></el-input>
        </el-form-item>
        <div class="flex r_btn">
          <el-button type="primary" @click="handleMainAdd(RIGHT['363'])" :disabled="!RIGHT['363']">新增</el-button>
        </div>
      </el-form>
      <el-table :data="MainTable.data" scrollbar-always-on>
        <el-table-column label="工单编号" prop="id" min-width="100px" fixed="left">
          <template #default="scope">GD-{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="问题描述" prop="describe" min-width="200px" show-overflow-tooltip></el-table-column>
        <el-table-column label="处理等级" prop="level" min-width="100px">
          <template #default="scope">
            {{ scope.row.level }}级
          </template>
        </el-table-column>
        <el-table-column label="工单类型" prop="type" min-width="120px"></el-table-column>
        <el-table-column label="工单状态" prop="status" min-width="120px">
          <template #default="scope">
            <div class="flex--center">
              <span class="dot" :style="{ background: statusColor[scope.row.status] || '#0079FE' }"></span>
              <span>{{ scope.row.status }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="工单来源" prop="comefrom" min-width="120px"></el-table-column>
        <el-table-column label="来源单号" prop="comefrom_id" min-width="120px"></el-table-column>
        <el-table-column label="所属区域" prop="position_info" min-width="180px" show-overflow-tooltip></el-table-column>
        <el-table-column label="所属站点" prop="unit_name" min-width="160px" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建人" prop="creater_name" min-width="120px"></el-table-column>
        <el-table-column label="创建时间" prop="create_time" min-width="160px"></el-table-column>
        <el-table-column label="操作" fixed="right" min-width="200px">
          <template #default="scope">
            <span class="flex-center-center">
              <span style="width: 28px;margin-right: 12px;">
                <template v-if="scope.row.status === '待派单' && scope.row.creater === info.id">
                  <el-button link type="primary" @click="handleMainEdit(RIGHT['364'], scope.row)" :disabled="!RIGHT['364']">
                    编辑
                  </el-button>
                </template>
              </span>
              <span style="width: 28px;margin-right: 12px;">
                <template v-if="scope.row.status === '待派单'">
                  <el-button link type="primary" @click="handleStep(RIGHT['366'], scope.row)" :disabled="!RIGHT['366']">
                    派单
                  </el-button>
                </template>
                <template v-else-if="scope.row.status === '待接单'">
                  <el-button link type="primary" @click="handleStep(RIGHT['367'], scope.row)" :disabled="!RIGHT['367']">
                    接单
                  </el-button>
                </template>
                <template v-else-if="scope.row.status === '待处理'">
                  <el-button link type="primary" @click="handleStep(RIGHT['368'], scope.row)" :disabled="!RIGHT['368']">
                    处理
                  </el-button>
                </template>
                <template v-else-if="scope.row.status === '待验收'">
                  <el-button link type="primary" @click="handleStep(RIGHT['369'], scope.row)" :disabled="!RIGHT['369']">
                    验收
                  </el-button>
                </template>
              </span>
              <el-button link type="primary" @click="handleStepView(scope.row)">查看</el-button>
              <el-button link type="danger" @click="handleMainDelete(RIGHT['365'], scope.row)" :disabled="!RIGHT['365']">删除</el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="->, total, prev, pager, next, sizes"
        background 
        :page-sizes="[10, 20, 30, 50, 100]"
        :pager-count="5"
        v-model:currentPage="Filter.page"
        v-model:page-size="Filter.pagesize"
        :total="MainTable.total"
      />
    </div>
  </div>
  
  <div class="popup">
    <el-drawer v-model="MainPopup.visible" size="980">
      <template #header>
        <div class="title-name">{{ MainPopup.type === '新增' ? '创建' : MainPopup.type }}工单信息</div>
      </template>
      <template #default>
        <div class="content-box">
          <el-form
            ref="MainFormRef"
            :model="MainForm.model"
            label-width="120px"
            class="flex t_form"
          >
            <div class="strong-name">工单信息</div>
            <el-form-item style="width: 50%;" prop="unit" label="所属站点：" :rules="[{required: true, message: '不能为空', trigger: 'change'},]">
              <div style="width: 90%" v-if="MainPopup.visible">
                <UnitByPosition :defaultLoadUnit="MainForm.model.unit" @current-change="unitChange" />
              </div>
            </el-form-item>
            <el-form-item style="width: 50%;" prop="addr" label="报障位置：">
              <el-input v-model="MainForm.model.addr" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item style="width: 50%;" prop="type" label="工单类型：" :rules="[{required: true, message: '不能为空', trigger: 'change'},]">
              <el-select v-model="MainForm.model.type" clearable>
                <el-option value="设备异常" label="设备异常"></el-option>
                <el-option value="系统异常" label="系统异常"></el-option>
                <el-option value="设备维护" label="设备维护"></el-option>
                <el-option value="生产事故" label="生产事故"></el-option>
                <el-option value="其他事件" label="其他事件"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 50%;" prop="level" label="处理等级：" :rules="[{required: true, message: '不能为空', trigger: 'change'},]">
              <el-select v-model="MainForm.model.level" clearable>
                <el-option value="一" label="一级"></el-option>
                <el-option value="二" label="二级"></el-option>
                <el-option value="三" label="三级"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 100%;" prop="describe" label="问题描述：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
              <el-input
                style="width: calc(50%*1.9 + 120px*0.05);"
                v-model="MainForm.model.describe"
                type="textarea"
                :rows="3"
              />
            </el-form-item>
            
            <div class="strong-name">资料信息</div>
            <el-form-item style="width: 100%;" prop="files" label="上传图片：">
              <UploadImage
                :files_json="MainForm.files_json"
                :updateTimes="MainForm.files_updateTimes"
                :maxSizeMB="5"
                @files-change="filesChange"
              />
              <div class="upload_info">请上传JPG/PNG/格式文件，不超过5MB</div>
            </el-form-item>
            <el-form-item style="width: 50%;" prop="fj" label="上传附件：">
              <UploadAttachment
                :fj_json="MainForm.fj_json"
                :updateTimes="MainForm.fj_updateTimes"
                :maxSizeMB="20"
                @files-change="fjChange"
              />
              <div class="upload_info">请上传其他格式文件，不超过20MB</div>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="MainPopup.visible = false">取 消</el-button>
          <el-button type="primary" @click="handleMainSubmit()">确 定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
  
  <Step
    v-if="stepPopup.type && stepPopup.content?.id"
    :type="stepPopup.type"
    :content="stepPopup.content"
    @close="closeStepMain"
  />
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
.view {
  width: 100%;
  height: 100%;
}
.mtncOrder-box {
  flex: 1;
  overflow: hidden;
  position: relative;
}
.dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 6px;
}
.popup {
  :deep(.el-drawer__header) {
    height: 60px;
    padding-bottom: 10px;
    margin-bottom: 0;
    border-bottom: 1px solid #EDEFF3;
    .title-name {
      font-weight: 500;
      font-size: 20px;
      color: #252525;
    }
  }
  :deep(.el-drawer__body) {
    padding-top: 0;
    overflow: hidden;
    display: flex;
  }
  :deep(.el-drawer__body .content-box) {
    flex: 1;
    position: relative;
    .strong-name {
      font-weight: 600;
      font-size: 14px;
      color: #111111;
      margin: 25px 0;
      width: 100%;
    }
  }
  :deep(.el-form-item__content) {
    align-content: flex-start;  /* 不加这个文本域以及上传资料之后对不齐 */
  }
}

/* 资料上传 */
.upload_info {
  font-size: 12px;
  color: #999999;
  line-height: 16px;
}

</style>